/*
 * @Author: 杨伟韦
 * @Date: 2025-07-21 22.20
 * @LastEditors: 杨伟韦
 * @LastEditTime: 2025-07-21 22.20
 * @Description: 保存相册
 */
import { inject } from 'vue';
import { saveUserTemplateJson } from '@/api/home';
import { debounce } from 'lodash-es';
export default function useSave(canvasEditor, albumEditor, { id }) {
  const saveListenerEvent = () => {
    // 画布变化监听
    canvasEditor.canvas.on('object:added', save);
    canvasEditor.canvas.on('object:removed', save);
    canvasEditor.canvas.on('object:modified', save);
    canvasEditor.canvas.on('path:created', save);
    canvasEditor.canvas.on('object:scaling', save);
    canvasEditor.canvas.on('object:rotating', save);
    canvasEditor.canvas.on('object:resizing', save);
    canvasEditor.canvas.on('object:moving', save);
    canvasEditor.canvas.on('object:skewing', save);
  };

  /**
   * 保存相册
   */
  const save = debounce(() => {
    const { onUpdateAlbum, getSelectAlbum } = albumEditor;
    const mSelectAlbum = getSelectAlbum();

    const currentJSON = canvasEditor.getJson();
    const selectAblum = mSelectAlbum;
    selectAblum.attributes.json = currentJSON;
    console.log(selectAblum, currentJSON);
    const ablums = onUpdateAlbum(selectAblum);

    // 删除缩略图，不然base64太大
    const _albums = ablums.map((item) => {
      const { src, ...other } = item || {};
      return other;
    });

    saveUserTemplateJson({
      templateJson: JSON.stringify(_albums),
      userTemplateId: id,
    });
  }, 500);

  return {
    save,
    saveListenerEvent,
  };
}
